package com.lixingye.meowstar.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixingye.meowstar.common.AppResult;
import com.lixingye.meowstar.common.ResultCode;
import com.lixingye.meowstar.dao.ArticleMapper;
import com.lixingye.meowstar.exception.ApplicationException;
import com.lixingye.meowstar.model.Article;
import com.lixingye.meowstar.model.Board;
import com.lixingye.meowstar.model.User;
import com.lixingye.meowstar.service.IArticleService;
import com.lixingye.meowstar.service.IBoardService;
import com.lixingye.meowstar.service.IUserService;
import com.lixingye.meowstar.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫大仙
 * @since 2025-01-14
 */
@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;

    /**
     * 发布帖子
     * @param article
     */
    @Override
    public void create(Article article) {
        //非空校验
        if(article==null || article.getBoardId()==null || article.getUserId()==null
           || StringUtil.isEmpty(article.getTitle())
           || StringUtil.isEmpty(article.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库
        int insert = articleMapper.insert(article);
        if(insert<=0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        User user = userService.getByUserId(article.getUserId());
        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败,useid= "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());

        //获取板块信息
        Board board = boardService.getById(article.getBoardId());
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败,boardid= "+article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString()+", userID = "+article.getId()+
                ", boardID = "+article.getBoardId()+", 发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if(boardId==null || boardId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.getById(boardId);
        if(board == null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+", boardId = "+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        if(articles==null) articles = new ArrayList<>();
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        Article article = articleMapper.selectDetailById(id);
        if(article==null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子的访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //返回帖子详情
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null || id<=0
                || StringUtil.isEmpty(title)
                ||StringUtil.isEmpty(content)
        ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectbById(Long id) {
        //非空校验
        if(id == null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectById(id);
        return article;
    }

    @Override
    public void thumbsUpById(Long id) {
        //校验
        if(id == null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子详情
        Article article = articleMapper.selectById(id);
        if(article==null || article.getDeleteState()==1 || article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        int i = articleMapper.updateById(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        if(id == null || id<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据ID查询帖子信息
        Article article = articleMapper.selectById(id);
        if(article==null || article.getDeleteState()==1 || article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString()+",article id = " +id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        int i = articleMapper.updateById(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        boardService.deleteOneArticleCountById(article.getBoardId());
        userService.deleteOneArticleCountById(article.getUserId());
        log.info(ResultCode.SUCCESS.toString()+",article id = "+id+"删除成功");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if(id == null || id<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子
        Article article = articleMapper.selectById(id);
        if(article==null || article.getDeleteState()==1 || article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString()+",article id = " +id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //更新
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        int i = articleMapper.updateById(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId == null || userId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.getByUserId(userId);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+", userId = "+userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }

}
